type DataType = 'boolean' | 'number' | 'string' | 'function' | 'array' | 'date' | 'regExp' | 'undefined' | 'null' | 'object' | 'formData';

/**
 * 判断数据类型
 * @param data - 要判断类型的数据
 * @returns {String} - 返回数据类型
 */
export function TypeOf(data: any): DataType {
  const toString = Object.prototype.toString;
  const map: Record<string, DataType> = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
    '[object FormData]': 'formData'
  };
  return map[toString.call(data)];
}

/**
 * 获取随机数
 * @param min - 最小值
 * @param max - 最大值
 */
export const Random = (min: number = 0, max: number = 10): number => {
  return Math.floor(Math.random() * (max - min + 1) + min);
};

interface TreeNode {
  [key: string]: any;
  children?: TreeNode[];
}

/**
 * 数组转树
 * @param data - 源数据数组
 * @param id - ID字段名
 * @param pid - 父ID字段名
 */
export function TreeDataTranslate(data: TreeNode[], id: string = 'id', pid: string = 'pId'): TreeNode[] {
  const resData = [...data];
  const res: TreeNode[] = [];
  const temp: { [key: string]: TreeNode } = {};

  for (let i = 0; i < resData.length; i++) {
    temp[resData[i][id]] = resData[i];
  }

  for (let k = 0; k < resData.length; k++) {
    if (temp[resData[k][pid]] && resData[k][id] !== resData[k][pid]) {
      if (!temp[resData[k][pid]]['children']) {
        temp[resData[k][pid]]['children'] = [];
      }
      temp[resData[k][pid]]['children']!.push(resData[k]);
    } else {
      res.push(resData[k]);
    }
  }
  return res;
}
